<template>
  <div class="list">
    <!-- 搜索 v-show="state.searchState.show"-->
    <Row class="search-filter" :class="{'active':searchState}">
      <Col>
        <Card style="height: 125px;">
          <Form :label-width="80" inline>
            <Form-item label="模板名称">
              <Input v-model="formItem.name" placeholder="请输入" style="width:187px"></Input>
            </Form-item>
            <Form-item label="模板编码">
              <Input v-model="formItem.code" placeholder="请输入" style="width:187px"></Input>
            </Form-item>
            <Form-item style="margin:0px 0px 0px -4vw;">
              <div class="clearfix">
                <span class="pull-right">
                  <Button type="primary" icon="ios-search" shape="circle" @click="queryTableList()">查询</Button>
                </span>
              </div>
            </Form-item>
          </Form>
        </Card>
      </Col>
    </Row>
    <!-- 搜索 /-->
    <Row>
      <Col>
        <Card>
          <div slot="title">
            <Icon type="ios-film-outline"></Icon>固定表头
            <Button type="dashed" @click.native="fixedHeader=!fixedHeader">
              <Icon type="pin"></Icon>
            </Button>
            <Button type="success" @click.native="addOpen()">
              <Icon type="plus"></Icon>新增
            </Button>
            <Button type="primary" @click="searchShow" shape="circle">
              <Icon type="funnel"></Icon>筛选
            </Button>
          </div>

          <a href="#" slot="extra" @click.prevent="refresh">
            <Icon type="ios-loop-strong"></Icon>
          </a>
          <Table :loading="TableLoading" :show-header="showHeader" :height="fixedHeader ? 350 : ''" :data="listData" :columns="columns1" ref="table"	@on-select="onSelect" @on-selection-change="onSelectionChange"></Table>
          <Row type="flex" justify="center">
            <Col>
              <Page :id="pageId" :total="totalSize" show-total show-sizer show-elevator @on-change="changeCurrent" @on-page-size-change="changePageSize" style="margin: 24px 0 24px;text-align:right"></Page>
            </Col>
            <Col push="1">
              <Button style="margin-top: 4vh;" type="primary" @click="goElevatorPage(pageId)">跳转</Button>
            </Col>
          </Row>
        </Card>
      </Col>
    </Row>
    <Modal v-model="routerModal" fullscreen>
      <router-view></router-view>
      <div slot="footer" style="display: none"></div>
    </Modal>
  </div>
</template>

<script>
import { fetchList, templateEnable, templateDel } from "@/api/wx";
export default {
  name: "list",
  components: {},
  data() {
    return {
      pageId:"targetPage", //跳转
      routerModal: false,
      currIndex: 0, // 当前编辑和新增的行号
      searchState: false,
      showHeader: true, // 是否显示表头 @:show-header
      TableLoading: false, // 分页loading
      fixedHeader: false, // 是否固定表头 @:height
      tableSize: "small", // @:size
      DateReady: false, // 判断异步数据加载完成，避免报错
      loadloading: false, // save
      currIndex: 0,
      saveDisabled: false,

      current: 1,
      totalSize: 0, //总条数
      start: 0, //开始条数
      limit: 10, //每页记录数

      formItem: {
        name: "",
        code: ""
      },

      listStyle: {
        width: "280px",
        height: "300px"
      },

      listData: [], // @:data 列表数据
      columns1: [
        //列表表头
        {
          title: "模板ID",
          key: "id",
          align: "center",
          tooltip: "true",
          fixed: "left"
        },
        {
          title: "模板编码",
          key: "code",
          align: "center",
          tooltip: "true"
        },
        {
          title: "模板名称",
          key: "name",
          align: "center",
          tooltip: "true"
        },

        {
          title: "Appid",
          key: "appId",
          align: "center",
          tooltip: "true"
        },

        {
          title: "调用微信模板",
          key: "wxTemplateId",
          align: "center",
          tooltip: "true"
        },

        {
          title: "状态",
          key: "status",

          render: (h, params) => {
            const row = params.row;
            const color = row.status === 1 ? "primary" : "error";
            const text = row.status === 1 ? "启用" : "停用";
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: color
                }
              },
              text
            );
          }
        },

        {
          title: "创建时间",
          key: "createDate",
          align: "center",
          tooltip: "true",
          render: (h, params) => {
            return h('div', this.changeDate(this.listData[params.index].createDate));
          }
        },

        {
          title: "修改时间",
          key: "updateDate",
          align: "center",
          tooltip: "true",
          render: (h, params) => {
            return h('div', this.changeDate(this.listData[params.index].updateDate));
          }
        },

        {
          title: "操作",
          key: "actor",
          align: "center",
          fixed: "right",
          width:200,
          render: (h, params) => {
            if (this.listData[params.index].status === 0) {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.editOpen(params);
                      }
                    }
                  },
                  "编辑"
                ),

                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.remove(params);
                      }
                    }
                  },
                  "删除"
                ),

                h(
                  "Button",
                  {
                    props: {
                      type: "info",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.change(params, 1);
                      }
                    }
                  },
                  "启用"
                )
              ]);
            } else {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.change(params, 0);
                      }
                    }
                  },
                  "停用"
                )
              ]);
            }
          }
        }
      ]
    };
  },
  watch: {
    params: {
      handler(val) {
        this.updateTableList(val);
      },
      deep: true
    },
    fixedHeader: {
      handler(val) {
        if (val) {
          this.$Message.info("表头已固定");
        }
      }
    },
    "add_info.contents": {
      handler(val) {
        this.add_info.length = this.add_info.contents.length;
      }
    }
  },
  computed: {
    state() {
      return this.$store.state.app;
    }
  },
  methods: {
    /** 格式化时间 */
    changeDate(value) {
      var dateee = new Date(value).toJSON();
      var date = new Date(+new Date(dateee)+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
      return date;
    },
    //筛选
    searchShow() {
      this.searchState = !this.searchState;
    },
    //	刷新页面
    refresh() {
      this.updateTableList(this.params);
    },
    //搜索
    queryTableList() {
      this.updateTableList(this.params);
    },

    //分页
    changePageSize(pageSize) {
      this.limit = pageSize;
      this.updateTableList();
    },
    changeCurrent(current) {
      this.start = current * this.limit - this.limit;
      this.updateTableList();
    },

    //列表
    updateTableList(params) {
      this.TableLoading = true;
      this.load = true;
      var reqParams = {
        name: this.formItem.name,
        code: this.formItem.code,
        communicationChannelTypeId: "6",
        start: this.start,
        limit: this.limit
      };
      fetchList(reqParams).then(res => {
        this.TableLoading = false;
        if (res.status == 200) {
          this.totalSize = res.data.total;
          this.listData = res.data.records;
          this.DateReady = true;
        } else {
          this.$Message.error(res.statusText);
        }
      });
    },

    onSelect(selection, row) {},

    onSelectionChange(selection) {
      this.params.limit = selection;
    },

    goElevatorPage(pageId){  // 跳转按钮
      var evtObj;
      var thisPage=document.getElementById(pageId);
      var elevatorDiv=thisPage.getElementsByClassName("ivu-page-options-elevator");
      if(elevatorDiv && elevatorDiv.length>0){
        var pageInput = elevatorDiv[0].getElementsByTagName("input")[0];
        if (window.KeyEvent) {//firefox 浏览器下模拟事件
          evtObj = document.createEvent('KeyEvents');
          evtObj.initKeyEvent("keyup", true, true, window, true, false, false, false, 13, 0);
        } else {//chrome 浏览器下模拟事件
          evtObj = document.createEvent('UIEvents');
          evtObj.initUIEvent("keyup", true, true, window, 1);
          delete evtObj.keyCode;
          if (typeof evtObj.keyCode === "undefined") {//为了模拟keycode
            Object.defineProperty(evtObj, "keyCode", { value: 13 });
          } else {
            evtObj.key = String.fromCharCode(13);
          }
        }
        pageInput.dispatchEvent(evtObj);
      }
    },

    //删除
    remove(params) {
      var _self = this;
      this.$Modal.confirm({
        title: "删除确认",
        content: `是否确认删除此条记录`,
        onOk: function() {
          this.$Loading.start();

          var reqParams = {
            id: params.row.id
          };

          templateDel(reqParams).then(res => {
            this.loading = false;

            if (res.data.code == 0) {
              this.$Message.info("删除成功！");
              _self.updateTableList();
            } else {
              this.$Message.error("删除失败!请稍后再试...!");
            }
          });
        }
      });
    },
    //更改状态
    change(params, status) {
      var _self = this;
      this.$Modal.confirm({
        title: "更改状态",
        content: `是否确认更改状态`,
        onOk: function() {
          this.$Loading.start();

          var reqParams = {
            id: params.row.id,
            status: status
          };

          templateEnable(reqParams)
            .then(res => {
              this.loading = false;

              if (res.data.code == 0) {
                this.$Message.info("更改状态成功！");
                _self.updateTableList();
                this.$Loading.destroy();
              }
            })
            .catch(error => {
              this.$Message.error("更改状态失败!请稍后再试...!");
              this.$Loading.destroy();
            });
        }
      });
    },

    addOpen() {
      this.$router.push({
        path: "/campaign/wxtemplate/add",
        query: { _button: true }
      });
      this.routerModal = true;
    },

    editOpen(params) {
      this.$router.push({
        path: "/campaign/wxtemplate/edit",
        query: { _button: true, _id: params.row.id }
        // 页面
      });
    }
  },
  created() {
    this.updateTableList(this.params);
  }
};
</script>

<style lang="less" scoped>
.search-filter {
  opacity: 0;
  display: none;
  overflow: hidden;
  transition: all 0.28s ease-out;
  &.active {
    opacity: 1;
    display: block;
  }
}
</style>
